//左侧和顶部菜单数据
import { ref, watch } from 'vue'
import { defineStore } from 'pinia'
export const useMenuStore = defineStore(
  'menu',
  () => {
    const isShowMenu = ref(true) //是否显示左侧和顶部菜单
    const leftMenu = ref([])
    const topMenu = ref([])
    const iframeSrc = ref('')
    const activeRoute = ref({
      label: '首页',
      path: '/home'
    })
    const activeRouteParent = ref({})
    const setLeftMenu = (arr) => {
      leftMenu.value = arr
    }
    const setTopMenu = (arr) => {
      topMenu.value = arr
    }
    const setActiveRoute = (obj) => {
      activeRoute.value = obj
    }
    const setActiveRouteParent = (obj) => {
      activeRouteParent.value = obj
    }
    watch(
      () => activeRoute,
      (route) => {
        if (route.value.path == '/home') {
          activeRouteParent.value = {}
        } else {
          const parent = leftMenu.value.find((item) => {
            if (item.children) {
              const result = item.children.find((subItem) => subItem.meta.title == route.value.label)
              if (result) {
                return item
              }
            }
          })
          activeRouteParent.value = parent || {}
        }
      },
      {
        deep: true,
        immediate: true
      }
    )
    return {
      isShowMenu,
      leftMenu,
      topMenu,
      activeRoute,
      activeRouteParent,
      iframeSrc,
      setLeftMenu,
      setTopMenu,
      setActiveRoute,
      setActiveRouteParent
    }
  },
  {
    persist: true
  }
)
